/**
 * 
 */
package com.fnic.pearl.scheduler.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fnic.pearl.scheduler.constant.CondHeaderField;
import com.fnic.pearl.scheduler.dao.SchedulerStore;
import com.fnic.pearl.scheduler.model.ProbeTaskStats;
import com.fnic.pearl.scheduler.model.TaskStats;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 查看当前任务统计信息
 * 
 * @author HuHaiyang
 * @date 2013年10月11日
 */
public class MTaskStatsServlet extends HttpServlet
{
    private static final Logger LOG = Logger.getLogger(MTaskStatsServlet.class);
    private static final long serialVersionUID = 1L;
    private Gson gson = new GsonBuilder()
        .excludeFieldsWithoutExposeAnnotation()
        .setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String[] values = request.getParameterValues(CondHeaderField.COND_PROBE_ID);
        if (values == null || values.length != 1)
        {
            TaskStats ts = SchedulerStore.getInstance().getStats();
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            
            response.getWriter().write(gson.toJson(ts));
            response.getWriter().flush();
            return;
        }
        
        int probeId = 0;
        try
        {
            probeId = Integer.valueOf(values[0]);
        }
        catch (NumberFormatException e)
        {
            LOG.warn("probeId format error: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        ProbeTaskStats ptstat = SchedulerStore.getInstance().getStats().getStats(probeId);
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        
        response.getWriter().write(gson.toJson(ptstat));
        response.getWriter().flush();
    }
}
